//
//  AIAlbumTool.swift
//  ai_assettool
//
//  Created by 李旭峰 on 2021/4/8.
//

import UIKit
import Photos

struct AIPhotoError : AIError {
    let error: String?
    let status:PHAuthorizationStatus
}

/**
 * 照片工具
 */
class AIPhotoTool: NSObject {
    typealias AuthAction = (_ success:Bool,_ error:AIError?)->Void
}

/**
 * 相册鉴权相关
 */
extension AIPhotoTool {
    fileprivate typealias AlbumAuthAction = AuthAction
    static func getAlbumAuthoritedStatus() -> PHAuthorizationStatus {
        if #available(iOS 14, *) {
            return  getAlbumAuthoritedStatus_ios14_after()
        }
        return PHPhotoLibrary.authorizationStatus()
    }
    
    @available(iOS 14, *)
    fileprivate static func getAlbumAuthoritedStatus_ios14_after() -> PHAuthorizationStatus {
        return PHPhotoLibrary.authorizationStatus(for: .readWrite)
    }
    
    static func requestAlbumAuthorited(autoRequest:Bool = false,action:@escaping AuthAction) {
        let status = getAlbumAuthoritedStatus()
        switch status {
        case .notDetermined:notDeterminedHandler(autoRequest: autoRequest, action: action)
        case .restricted:restrictedHandler(action)
        case .authorized:authorizedHandler(action)
        case .denied:deniedHandler(action)
        case .limited:limitedHandler(autoRequest: autoRequest, action: action)
        default:break
        }
    }
    
    /// 要访问照片库，必须具有明确的用户许可权，但该用户尚未授予或拒绝这种许可权
    fileprivate static func notDeterminedHandler(autoRequest:Bool,action:@escaping AlbumAuthAction){
        if !autoRequest {
            action(false,AIPhotoError(error: "尚未进行相册权限申请", status:.notDetermined))
            return
        }
        PHPhotoLibrary.requestAuthorization { (status) in
            requestAlbumAuthorited(autoRequest: autoRequest, action: action)
        }
    }
    
    /// 您的应用无权访问照片库，并且用户无法授予此类权限
    fileprivate static func restrictedHandler(_ action:AlbumAuthAction){
        action(false,AIPhotoError(error: "相册权限访问受限", status:.restricted))
    }
    
    /// 用户已明确授予您的应用访问照片库的权限
    fileprivate static func authorizedHandler(_ action:AlbumAuthAction){
        action(true,nil)
    }
    
    /// 用户已明确拒绝您的应用访问照片库
    fileprivate static func deniedHandler(_ action:AlbumAuthAction){
        action(false,AIPhotoError(error: "用户拒绝访问相册权限", status:.denied))
    }
    
    fileprivate static func limitedHandler(autoRequest:Bool = false,action:AlbumAuthAction){
        action(true,nil)
    }
    
    static func openSetting(){
        guard let url = URL(string: UIApplication.openSettingsURLString) else {
            return
        }
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
}

/**
 * 获取照片 - 相册操作
 */
extension AIPhotoTool {
    
    /// 查询所有的相册
    /// TODO: 如何合并两个 PHFetchResult
    /// - Returns: 返回相册列表
    fileprivate static func fetchAllAlbums() -> PHFetchResult<PHAssetCollection> {
//        var smartResult = fetchSmartAlbums()
//        let albumResult = fetchUserCollections()
        return PHFetchResult()
    }
    
    /// 查询所有的智能相册
    /// - Returns: 智能相册列表
    static func fetchSmartAlbums() -> PHFetchResult<PHAssetCollection> {
        let fetchResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil)
        return fetchResult
    }
    
    /// 查询所有的用户相册
    /// - Returns: 用户相册列表
    static func fetchUserAlbums() -> PHFetchResult<PHAssetCollection> {
        let fetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
        return fetchResult
    }
    
    /// 使用 唯一标识符 查找 指定相册
    /// - Parameters:
    ///   - localIdentifier: localIdentifier: 唯一标识符
    ///   - type: 相册类型，只支持查找 只能相册 和 用户相册，不支持查询临时相册
    /// - Returns: 执行相册
    static func fetchAlbum(_ localIdentifier:String,type:PHAssetCollectionType? = nil) -> PHAssetCollection? {
        guard let albumType = type else {
            let smartCollection = fetchSmartAlbum(localIdentifier)
            if smartCollection != nil {
                return smartCollection
            }
            return fetchUserAlbum(localIdentifier)
        }
        switch albumType {
        case .album:return fetchUserAlbum(localIdentifier)
        case .smartAlbum:return fetchSmartAlbum(localIdentifier)
        default:return nil
        }
    }
    
    /// 使用 唯一标识符 在 智能相册列表中查找指定相册
    /// - Parameter localIdentifier: 相册标识符
    /// - Returns: 指定相册，可能为空
    static func fetchSmartAlbum(_ localIdentifier:String) -> PHAssetCollection? {
        let fetchResult = fetchSmartAlbums()
        var albumResult:PHAssetCollection? = nil
        fetchResult.enumerateObjects { (album, _, stop) in
            if localIdentifier.count >= 1 && localIdentifier == album.localIdentifier {
                albumResult = album
                stop.pointee = true
            }
        }
        return albumResult
    }
    
    /// 使用 唯一标识符 在 用户相册列表 中查找指定相册
    /// - Parameter localIdentifier: 相册标识符
    /// - Returns: 指定相册，可能为空
    static func fetchUserAlbum(_ localIdentifier:String) -> PHAssetCollection? {
        let fetchResult = fetchUserAlbums()
        var albumResult:PHAssetCollection? = nil
        fetchResult.enumerateObjects { (album, _, stop) in
            if localIdentifier.count >= 1 && localIdentifier == album.localIdentifier {
                albumResult = album
                stop.pointee = true
            }
        }
        return albumResult
    }
    
    /// 查询 指定相册下 所有的资源
    /// - Parameters:
    ///   - collection: 相册
    ///   - options: 筛选想
    /// - Returns: 资源列表
    static func fetchAssets(_ collection:PHAssetCollection, options:PHFetchOptions? = nil) -> PHFetchResult<PHAsset> {
        let assets = PHAsset.fetchAssets(in: collection, options: options)
        return assets
    }
    
    /// 查找指定的相册下的所有资源
    /// - Parameters:
    ///   - albumIdentifier: 相册唯一标识
    ///   - options: 符合条件
    /// - Returns: 资源列表
    static func fetchAssetsWithAlbum(_ albumIdentifier:String, options:PHFetchOptions? = nil) -> PHFetchResult<PHAsset> {
        guard let album = fetchAlbum(albumIdentifier) else {
            return PHFetchResult()
        }
        return fetchAssets(album, options: options)
    }
    
    /// 查找指定的智能相册下的所有资源
    /// - Parameters:
    ///   - albumIdentifier: 智能相册唯一标识
    ///   - options: 符合条件
    /// - Returns: 资源列表
    static func fetchAssetsWithSmartAlbum(_ albumIdentifier:String,options:PHFetchOptions? = nil) -> PHFetchResult<PHAsset> {
        guard let smartAlbum = fetchSmartAlbum(albumIdentifier) else {
            return PHFetchResult()
        }
        return fetchAssets(smartAlbum, options: options)
    }
    
    /// 查找指定的用户相册下的所有资源
    /// - Parameters:
    ///   - albumIdentifier: 用户相册唯一标识
    ///   - options: 符合条件
    /// - Returns: 资源列表
    static func fetchAssetsWithUserAlbum(_ albumIdentifier:String, options:PHFetchOptions? = nil) -> PHFetchResult<PHAsset> {
        guard let userAlbum = fetchUserAlbum(albumIdentifier) else {
            return PHFetchResult()
        }
        return fetchAssets(userAlbum, options: options)
    }
    
    /// 查找 所有资源
    /// - Returns: 资源列表
    static func fetchAllAssets() -> PHFetchResult<PHAsset> {
        let allPhotosOptions = PHFetchOptions()
        allPhotosOptions.sortDescriptors = [
            NSSortDescriptor(
                key: "creationDate",
                ascending: false
            )
        ]
        let allPhotos:PHFetchResult<PHAsset> = PHAsset.fetchAssets(with: allPhotosOptions)
        return allPhotos
    }
    
    
    /// 使用资源唯一标识符查找指定的资源
    /// - Parameter localIdentifier: 资源的唯一标识符
    /// - Returns: 资源
    static func fetchAsset(_ localIdentifier:String) -> PHAsset? {
        let predicate = NSPredicate(format: "localIdentifier = %@", localIdentifier)
        let options = PHFetchOptions()
        options.predicate = predicate
        let fetchResult = PHAsset.fetchAssets(with: options)
        var assetResult:PHAsset? = nil
        fetchResult.enumerateObjects { (asset, _, stop) in
            if localIdentifier.count >= 1 && localIdentifier == asset.localIdentifier {
                assetResult = asset
                stop.pointee = true
            }
        }
        return assetResult
    }
}
typealias AIPhotoRequestPathHandler = (_ path:String?) -> Void
extension PHAsset {
    func requestPath(didFinished:AIPhotoRequestPathHandler? = nil) {
        let options = PHContentEditingInputRequestOptions()
        options.isNetworkAccessAllowed = true
        self.requestContentEditingInput(with: options) { (input, info) in
            guard let tempInput = input else {
                didFinished?(nil)
                return
            }
            if PHAssetMediaType.video == tempInput.mediaType {
                let videoURL = (input?.value(forKey: "_videoURL") as? URL)?.absoluteString
                didFinished?(videoURL)
            } else if PHAssetMediaType.image == tempInput.mediaType {
              didFinished?(tempInput.fullSizeImageURL?.absoluteString)
            }
        }
    }
  func requestThumbPath(didFinished:AIPhotoRequestPathHandler? = nil) {
    PHCachingImageManager.default().requestImage(
      for: self,
      targetSize: CGSize(width: 200, height: 200),
      contentMode: .aspectFit,
      options: nil) { (image, info) in
      guard let tempImage = image else {
        didFinished?(nil)
        return
      }
      tempImage.saveImage { (path, error) in
        didFinished?(path)
      }
    }
  }
  fileprivate var imageThumb:UIImage {
    get {
      return UIImage()
    }
  }
  
  fileprivate var videoThumb:UIImage {
    get {
      return UIImage()
    }
  }
}


//func syncAction(_ waitAction:@escaping ()->Void,_ signalAction:@escaping ()->Void) {
//  let sema = DispatchSemaphore(value: 0)
//  DispatchQueue.global().async {
//    waitAction()
//    sema.signal()
//  }
//  sema.wait()
//}
